var colors = require('../../utils/colors.js')
const app = getApp()
const db=wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    weekArray: ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周', '第7周', '第8周', '第9周', '第10周', '第11周', '第12周', '第13周', '第14周', '第15周', '第16周', '第17周', '第18周', '第19周', '第20周', '第21周'],
    pageNum: 0, // 当前所在分类的索引
    todayDay: '', // 今日日期
    todayMonth:'', // 今日月份
    todayWeek:'', // 今日周
    day:'', // 日期
    month: '', // 月份
    monthNum:1,
    week: ['日','一', '二', '三', '四', '五', '六'], // 周日为起始日
    nowDay:[1,2,3,4,5,6,7], // 本周的七天日期
    schoolTime: ['2022','02','21'], // 本学期开学时间
    nowWeek: '', // 当前周
    XH:0,
    _openid:'',
    course_time:[
      ['8:05',''],
      ['','9:25'],
      ['9:40',''],
      ['',''],
      ['','12:00'],
      ['13:40',''],
      ['',''],
      ['','16:00'],
      ['',''],
      ['18:30',''],
      ['',''],
      ['','20:50'],
  ],
    wList: [
      

  ]},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    app.getOpenid.then(openid => {
        console.log('获取的全局openid',openid)
        this.setData({
        _openid: openid
        })
        wx.setStorageSync('openid', openid) //把用户openid信息缓存到本地
        db.collection('student').where({
            _openid:this.data._openid
        }).get().then(res=>{
            console.log('缓存')
            wx.setStorageSync('userInfo', res.data[0])
            this.setData({
                XH:Number(res.data[0].id)
            })
            this.setData({
                wList:wx.getStorageSync('wlist')
            })
            db.collection('leave').where({
                id:res.data[0].id,
                progress:'1',
                result:'1',
                update:'0'
            }).get().then(res=>{
               if(res.data.length==0){ //没有请假更新
                   
               }
               else{ //有请假更新
                for (var n=0;n<res.data[0].class1.length;n++){
                    let course_id=res.data[0].class1[n]._id
                    const _ = db.command
                    console.log(course_id)
                    db.collection('course').doc(course_id).update({
                        data:{
                            LEAVE:1
                        },
                    })
                }
                let update_id=res.data[0]._id
                console.log(update_id)
                db.collection('leave').doc(update_id).update({
                    data:{
                        update:'1'
                    }
                })
                console.log(this.data.wList.length)
                var wlist2=[]
                for (var i=1;i<=16;i++){
                    db.collection("course").where({
                        ZC:i,
                        XH:this.data.XH
                    }).get().then(res=>{
                        var wlist2_week=new Array()
                        var coursedata=res.data
                        for (var j=0;j<coursedata.length;j++){
                            var color=Math.floor((Math.random()*15)+1)
                            if(coursedata[j].LEAVE==1){
                                console.log(coursedata[j])
                                wlist2_week.push({"id":16,"isToday":coursedata[j].XQJ,"jie":coursedata[j].KSJ,"classNumber":coursedata[j].JSJ-coursedata[j].KSJ+1,"name":coursedata[j].KCMC,"address":coursedata[j].JSMC})}
                                else{
                                wlist2_week.push({"id":color,"isToday":coursedata[j].XQJ,"jie":coursedata[j].KSJ,"classNumber":coursedata[j].JSJ-coursedata[j].KSJ+1,"name":coursedata[j].KCMC,"address":coursedata[j].JSMC})
                                }
                        }
                        wlist2.push(wlist2_week)
       
                        
                    })
                }
                
                setTimeout(() => {
                    // 在这里面插入必须在后面执行的代码
                    this.setData({
                        wList:wlist2
                    })
                    wx.setStorageSync('wlist', wlist2)
                  }, 1500) // 0.5秒后执行代码
                
               }
               if(this.data.wList.length<5){
                var wlist2=[]
                for (var i=1;i<=16;i++){
                    db.collection("course").where({
                        ZC:i,
                        XH:this.data.XH
                    }).get().then(res=>{
                        console.log(res)
                        var wlist2_week=new Array()
                        var coursedata=res.data
                        for (var j=0;j<coursedata.length;j++){
                            var color=Math.floor((Math.random()*15)+1)
                            if(coursedata[j].LEAVE==1){
                                console.log(coursedata[j].LEAVE)
                                console.log(coursedata[j].LEAVE)
                                wlist2_week.push({"id":16,"isToday":coursedata[j].XQJ,"jie":coursedata[j].KSJ,"classNumber":coursedata[j].JSJ-coursedata[j].KSJ+1,"name":coursedata[j].KCMC,"address":coursedata[j].JSMC})}
                                else{
                                wlist2_week.push({"id":color,"isToday":coursedata[j].XQJ,"jie":coursedata[j].KSJ,"classNumber":coursedata[j].JSJ-coursedata[j].KSJ+1,"name":coursedata[j].KCMC,"address":coursedata[j].JSMC})
                                }
                        }
                        wlist2.push(wlist2_week)
                        
                    })
                }
                
                setTimeout(() => {
                    // 在这里面插入必须在后面执行的代码
                    this.setData({
                        wList:wlist2
                    })
                    wx.setStorageSync('wlist', wlist2)
                  }, 1500) // 0.5秒后执行代码



            }}
            )


        })
        })
    let nowWeek = this.getNowWeek()
    let nowDay = this.getDayOfWeek(nowWeek)
    let pageNum = nowWeek - 1
    let month = this.getMonth((nowWeek - 1) * 7);
    this.data.todayMonth
    this.setData({
      nowWeek,
      nowDay,
      pageNum,
      todayWeek:nowWeek,
      monthNum: month / 1, // 当前月份数字类型，用于数字运算
      colorArrays: colors // 课表颜色
    })

       
 

        // 在这里面插入必须在后面执行的代码

   
  },

  // 获取第几周后的月份
  getMonth(days) {
    let [year,month,day] = this.data.schoolTime
    var date = new Date(year,month-1,day);    
    date.setDate(date.getDate() + days);//获取n天后的日期      
    var m = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);        
    return  m;     
  },

  // 获取第几周后的星期几的日期
  getDay(days) {
    let [year, month, day] = this.data.schoolTime
    var date = new Date(year, month-1, day);
    date.setDate(date.getDate() + days);//获取n天后的日期      
    var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();//获取当前几号，不足10补0    
    return d;
  },

  // 获取当前周
  getNowWeek(){
    var date = new Date();
    let [year, month, day] = this.data.schoolTime
    var start = new Date(year, month-1, day);
    //计算时间差
    var left_time = parseInt((date.getTime()-start.getTime())/1000)+24 * 60 * 60;
    var days = parseInt(left_time/3600/24);
    var week = Math.floor(days / 7) + 1;
    var result = week
    if(week>20 || week <= 0){
      result = this.data.now_week;
    }
    return result
  },
  util: function (currentStatu) {
    var animation = wx.createAnimation({
      duration: 100, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });
    this.animation = animation;
    animation.opacity(0).rotateX(-100).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      this.setData({
        animationData: animation
      })

      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  //获取一周的日期
  getDayOfWeek(week){
    var day = []
    for (var i = -1; i < 6; i++) {
      var days = (week - 1) * 7 + i;
      day.push(this.getDay(days))
    }
    return day
  },

  // 获取课表数据
  async getCourseList(){

  },



    this.setData({
      cardView: cardView
    })
    this.util("open");
  },

  hideModal() {
    this.util("close");
  },

  // 点击切换导航的回调
  changeNav(event){
    let pageNum = event.currentTarget.dataset.page
    let nowWeek = pageNum + 1
    let nowDay = this.getDayOfWeek(nowWeek)
    let month = this.getMonth((nowWeek-1)*7)
    this.setData({
      pageNum,
      nowWeek,
      nowDay,
      month,
      monthNum: month / 1, // 当前月份数字类型，用于数字运算
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      todayDay: new Date().getDate(),
      todayMonth: new Date().getMonth() + 1,
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})